
var db;
var findUrl = "";
var contentValue = "";

/** current user info **/
var name = "";
var userid;
var nick = "";

/** current moim info **/
var current_moim;
var current_pos = "";
var current_memId;
var current_moim_title ="";

/**server **/
var url="http://10.201.208.196:8080";


function dbinit() {
	db = window.openDatabase("moim_db", "1.0", "Just a C4 DB", 200000); //will create database Dummy_DB or open it
}

//create table and insert some record
function setupTable(tx) {
	console.log("setupTable start");
	tx.executeSql("CREATE TABLE IF NOT EXISTS MOIM_BOARD "+
			"(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, content TEXT NOT NULL, regdate TEXT NOT NULL)");
	console.log("setupTable end");
}

//function will be called when an error occurred
function dbErrorHandler(err) {
	alert("Error processing SQL: " + err.code);
	console.log("Error processing SQL " + err.code);
}

//function will be called when process succeed
function showBoard() {
	db.transaction(queryDB, dbErrorHandler);
}

//select all from SoccerPlayer
function queryDB(tx) {
	console.log("queryDB!!!!!");
	tx.executeSql('SELECT * FROM MOIM_BOARD', [], renderList,
			dbErrorHandler);
}

function renderList(tx, result) {
}

function successCB() {}

 function onDeviceReady() {
 //logcat에 로그..
 console.log("onDeviceReady");
 // 10초간 SplashScreen이 보여지라고 하였지만, deviceready상태가 되면 무조건 SplashScreen을 닫는다.
 cordova.exec(null, null, "SplashScreen", "hide", []);
 // 저장된 정보 확인.
 //getEntries(); 

 document.addEventListener("menubutton", onMenuKeyDown, false);
 }    

/**********************************************/

 $("[data-role=page]").live("pageshow", function() {
	 
	 logoutOpen = false;
	 if(this.id=="plaza" || this.id == "plaza_write" || this.id=="update_pb" 
		 || this.id=="update_plaza" || this.id=="plaza_board_write") {
		 if(current_pos == 'man')
			 $(".hide").css({display:'none'});
	 }
  	
  	//check pageids
  	if(this.id=="moims") {
 		readMoimList();
 		current_moim_title="";
 	}
  	
  	else if(this.id=="main") {
  		current_moim_title=""
  	}
 	
  	else if(this.id == "moim"){
		moim(current_moim, current_pos, current_moim_title);
		getMembers(0);
	}
 	
  	else if (this.id == "create2") {
		$("#king_name").text(name);
		var moimTitle = localStorage.getItem('moimTitle');
		$('h2').text(moimTitle);
		localStorage.removeItem('moimTitle');
		posList('man');
		posList('noble');
	}
 	
  	else if(this.id=="board") {
		getMembers(1);
	}
  	
  	else if(this.id=="plaza_write") {
  		if(current_pos == 'man') {
			$.mobile.changePage('plaza.jsp');
		}
  	}
 	
  	else if(this.id=="plaza") {
		plazaList();
	}
  	
  	else if(this.id == "login") {
  		if(name.length > 0) {
  			console.log("[on page load] : already logged in");
  			$.mobile.changePage("moim_list.jsp");
  		}
  	}
  	
  	/** board updates **/
  	else if(this.id=='update_board') {
  		updateInit('board');
  	}
  	
  	else if(this.id=='update_plaza') {
  		if(current_pos == 'man') {
  			$.mobile.changePage('plaza.jsp');
  		}
  		updateInit('plaza');
  	}
  	
  	else if(this.id=='update_pb') {
  		updateInit('pb');
  	}
  	
  	if(this.id != 'signup' && name.length <= 0) {
  		$.mobile.changePage("login.jsp");
  		console.log("not logged in");
  		return;
  	}

  	if(current_moim_title != ""){
  		$("[data-role=header] h2").text(current_moim_title);
  	} 
});

 
/**********moim list ***********/
var leftArray = [15, 60, -5, 30, 15, -3];
var topArray = [330, 270, 410, 310, 440, 250];

 function readMoimList() {
	var cnt = 0;
	console.log("[readMoimList] for user : " + name);
     $.ajax({
         url : url + "/moimserver/json/user/login.json?name=" + name,
         dataType : "jsonp",
         crossDomain:true,
         jsonp :"callback",
         success : function(jsonData){
         	$.each(jsonData, function(k, v) {
         		var title = v.Moim.title;
         		var moimId = v.Moim.id;
         		var pos = v.pos;
         		var cover = v.Moim.coverNum;
         		
            	$("#my_moims").append("<div class=\'moim" + k + "\'>" + 
            			"<a href=\'#\' onclick=\'moim(" + moimId + ", &quot;" + pos + "&quot;, &quot;" + title + "&quot;)\'>" +
            			"<img src=\'img/cover"+ cover + ".png\'><br/>" +
            			title + "/" + pos + "</a></div>");
            	
            	var i = (k%leftArray.length);
            	var l_offset = (k/leftArray.length) * 720;
            	
            	$(".moim" + k).css({
            		left:leftArray[i] + l_offset, 
            		top:topArray[i]
            	});
            	cnt++;
         	});

        	$("#my_moims").css({width: cnt*130});
 			$("#my_moims").trigger("create");
         }
		
	}); //ajax (JSON)

 }

 /********moim ******/
 /* 서버에서 해당 모임 정보 불러옴 */
 function moim(moimId, pos, title) {

	 current_moim = moimId;
	 current_pos = pos;
	 current_moim_title=title;
	 if(pos == "man") {
			$.mobile.changePage("plaza.jsp");
			return;
		}
	 
     $.mobile.changePage("moim.jsp");

   //get member list
   $.ajax({
       url : url + "/moimserver/json/moim/userList.json?id=" + moimId,
       dataType : "jsonp",
       crossDomain:true,
       jsonp : "callback",
       success : function(jsonData){
			console.log("[moim] success getting user list for this moim");
			$.each(jsonData.member, function(k, v) { 
	    		var memberId = v.id;
	    		var userId = v.userId;
	    		
	    		//지금 모임에서 로그인된 유저의 멤버아이디...
	    		if(userId == userid) {
	    			current_memId = memberId;
	    		}
	        	$("#my_cur_moim").append("<p> member " + k + " : " + memberId + " / " + userId + "</p>");
	
				$("#my_cur_moim").trigger("create");
			});
       }
	}); //ajax (JSON)
}

/****create_moim_2****/

function setPos(item, pos) {
	if(pos == "king") {
		$("#king_name").text($(item).text());
	}
}

/* 멤버 추가하는 페이지에서 팝업메뉴로 가입된 유저 목록 불러옴 */
function posList(pos) {
    var popdiv;
    var popcont;
    if(pos == 'noble') {
    	popdiv = $("#noble_pop");
        popdiv.append('<fieldset id="member_list_noble" data-role="controlgroup">');
    } else if(pos == 'man') {
    	popdiv = $("#man_pop");
        popdiv.append('<fieldset id="member_list_man" data-role="controlgroup">');
    }
    
     if(pos == 'noble') {
     	popcont = $("#noble_pop #member_list_noble");
     } else if(pos == 'man') {
     	popcont = $("#man_pop #member_list_man");
     }
     $.when( $.ajax({
	         url : url + "/moimserver/json/user/list.json",
	         dataType : "jsonp",
	         crossDomain:true,
	         jsonp : "callback",
	         success : function(jsonData){
	 			$.each(jsonData, function (k, v) {
	 	    		popcont.append('<input type="checkbox" name="cb-'+k+'" id="cb-'+k+
	 	    			 '" value="'+v.nickname+'"/><label for="cb-'+k+'">'+v.nickname+'</label>');
	 			});
	         }
	 		
	 	}) 	).done( function () {
 	 	
 	     popcont.append('<a href="#" onclick=\'showSelectedNames(\"'+ pos+
 	    		 '\");\' data-role=\"button\" data-rel=\"back\" id=\'donebtn\'> done</a>');
 	     
 	     popdiv.trigger("create");
 	});
}

function addMember() {
	
	var moimid = localStorage.getItem("moim_id");

	var array = JSON.parse(localStorage.getItem("memberArray"));
	
	localStorage.removeItem("moim_id");
	localStorage.removeItem("memberArray");

	addMemberList(array, moimid, array.length);

	$.mobile.changePage("moim_list.jsp");
}

function addMemberList(array, moimid, i) {
	if(i <= 0) {
		return;
	}
	var nameToAdd = array[i-1].name;
	var posToAdd = array[i-1].pos;
	$.ajax({
	       url: url + "/moimserver/json/user/addMoim.json",
	       type: 'GET',
	       contenttype:'application/json; charset=utf-8',
	       crossDomain:true,
	       data: {
	          name: nameToAdd,
	          moimId: moimid,
	          pos: posToAdd
	       },
	       dataType:'jsonp',
	       success: function(jsonData) {
	    	   addMemberList(array, moimid, i-1);
	       },
	       error: function() {
	    	   console.log("[addMember] errorr...");
	       }
	}); //ajax
}
/* 페이지에 랭크별로 선택된 멤버 리스트 출력 */
function showSelectedNames(pos){
	
	var array = JSON.parse(localStorage.getItem("memberArray"));
	
	if(array == null) 
		array = [];
    if (pos == 'noble') {
    	var cnt = $("#member_list_noble input:checked").length;
		$("#noble_selected").empty();
    	for(var i=0; i<cnt; i++) {
    		$("#noble_selected").append("<li>" + $("#member_list_noble input:checked")[i].value + "</li>");
        	$("#noble_selected").listview('refresh');
        	var item = {"name": $("#member_list_noble input:checked")[i].value, "pos":'noble'};
        	array.push(item);
    	}
    } else if (pos == 'man') {
    	var cnt = $("#member_list_man input:checked").length;
		$("#man_selected").empty();
    	for(var i=0; i<cnt; i++) {
    		$("#man_selected").append("<li>" + $("#member_list_man input:checked")[i].value + "</li>");
        	$("#man_selected").listview('refresh');
        	var item = {"name": $("#member_list_man input:checked")[i].value, "pos":'man'};
        	array.push(item);
    	}
    }

	localStorage.setItem("memberArray", JSON.stringify(array));
    
}

function addMoim() {
	var title = document.getElementById("moim_title").value;
	var cover = parseInt($("#covers input[name='cover']:checked").val());
	localStorage.setItem('moimTitle', title);
	
	console.log("[addMoim] cover:" + $("#covers input[name='cover']:checked").val());

	$.ajax({
	       url: url + "/moimserver/json/moim/addMoim.json",
	       type: 'GET',
	       contenttype:'application/json; charset=utf-8',
	       crossDomain:true,
	       jsonp:"callback",
	       jsonpCallback:'jsonpHandler',
	       data: {
	          userName: name,
	          title:title,
	          content:'bar',
	          cover:cover	        	
	       },
	       dataType:'jsonp',
	       success: function (jsonData) {
	    	   console.log("[addMoim] successsssssssss: " + jsonData.moim_id);

	    	   
	    	   localStorage.setItem("moim_title", title);
	    	   localStorage.setItem("moim_id", jsonData.moim_id);
	    	   
	    	   $.mobile.changePage("create_new_moim_2.jsp");
	       },
	       error: function() {
	    	   console.log("[addMoim] errorr...");
	       }
	});

//	   $.mobile.changePage("create_new_moim_2.jsp");

}


/******signup******/

function checkpw() {
	var p1 = document.getElementById("passwd").value;
	var p2 = document.getElementById("passwd_confirm").value;
	
	return p1 == p2;
} 

function signup() {

	//credential check.
	var okToGo = true;
	$("#errormsg").text("");
	
	var nick = document.getElementById("nickName").value;
	if(nick == "") {
		console.log("nickname empty");
		$("#errormsg").append("닉네임을 입력하세요<br/>");
		$("#nickname").focus();
		okToGo = false;
	}
	
	var username = document.getElementById("name").value;
	if(username == "") {
		console.log("username empty");
		$("#errormsg").append("아이디를 입력하세요<br/>");
		$("#nickname").focus();
		okToGo = false;
	}
	
	var passwd = document.getElementById("passwd").value;
	if(passwd == "") {
		console.log("passwd empty");
		$("#errormsg").append("패스워드를 입력하세요<br/>");
		$("#nickname").focus();
		okToGo = false;
	}
	
	if(!checkpw()) {
		$("#errormsg").append("패스워드가 다릅니다<br/>");
		okToGo = false;
	}
	
	if(!okToGo) {
		return;
	}
	
	console.log("[signup]: " + nick + " / " + username + " / " + passwd);
	$.ajax({
	       url: url + "/moimserver/json/user/signup.json",
	       type: 'GET',
	       contenttype:'application/json; charset=utf-8',
	       crossDomain:true,
	       jsonp : "callback",
	       jsonpCallback:'jsonpHandler',
	       data: {
	          nickName: nick,
	          name:username,
	          passwd:passwd
	       },
	       dataType:'jsonp',
	       success: function (jsonData) {
	    	   console.log("[signup] : " + jsonData.result);
	    	   $.mobile.changePage("main.jsp");
	       }
	});
//	$.mobile.changePage("main.jsp");
}

/********board***********/

function boardWrite() {
	var title = document.getElementById("title").value;
	var content = document.getElementById("write-textarea").value;
	console.log("[boardWrite] memberid? " + current_memId);
	$.ajax({
	       url: url + "/moimserver/json/member/writeBoard.json",
	       type: 'GET',
           crossDomain:true,
           jsonp : "callback",
	       contenttype:'application/json; charset=utf-8',
	       data: {
	    	  memberId : current_memId,
	          title: title,
	          content:content
	       },
	       dataType:'jsonp', 
	       success: function(jsonData) {
	    		console.log("[boardWrite] board write done:" + jsonData.result);
	    		$.mobile.changePage("moim.jsp");
	       }
	});
}


function boardList(array, i) {
	if (i <= 0) {
		return;
	}
	
    $.ajax({
        url : url + "/moimserver/json/member/boardList.json?memberId=" + array[i-1].memId,
        dataType : "jsonp",
        crossDomain:true,
        jsonp : "callback",
        success : function(jsonData){
        	$.each(jsonData.boars, function(k, v) {
        		var notCollap = "";
        		if(k == 0 && i == array.length) {
        			notCollap = " data-collapsed='false'";
        		}
        		$("#board-list").append(
        				"<li data-role=\"collapsible\"  data-icon='arrow-d' data-iconpos='right' " +
        				notCollap + "data-theme='z' data-content-theme='d'>" +
        				"<h4>" +
        				"<div class='author'><img src='img/p" + array[i-1].userId + ".jpg' alt='profile'><br/>" +
        				"<span class='author_name'>" + array[i-1].nickname + "</span></div>" +
        				"<span class='rtitle'>" + v.title + "</span>" + 
        				"<div class='date'>" + v.regdate + "</div>" + 
        				"</h4>" + 
        				"<p>" + v.content + "</p>"+
        				"<fieldset data-role='controlgroup' data-type='horizontal' style='text-align:right;' id='btn_" +v.id + "' >" +
        				"</fieldset>" +
        				"<ul id='board_comment_" + v.id + "'></ul></li>");
        		
        		if(userid == array[i-1].userId) {
        			$("#btn_" + v.id).append(
            				"<a href='#' onclick='update(&#39;board&#39;, " + v.id + ")' data-role='button' data-theme='z' data-mini='true'>수정</a>" +
            				"<a href='#' onclick='remove_item(&#39;board&#39;, " + v.id + ")' data-role='button' data-theme='z' data-mini='true'>삭제</a>");
        		}
        		attachComment(v.id);
        		
        	});
        	
        	boardList(array, i-1);
    		$("#board-list").trigger('create');
    		$("[data-role=\"collapsible\"]").collapsible();
        	$("#ajax").show();
        }
		
	}); //ajax
	
}

function attachComment(boardId) {
	var boardComment = $("#board_comment_" + boardId);

	//댓글작성부
	boardComment.append ("<li class='comment_write'>" + 
	"<div style='width:100%;'>" +
		"<div class='comment-text' >" +
		"<input type='text' id='comment_text_" + boardId  + "' name='comment_text_" + boardId  + "' data-mini='true'"+
		"data-corners='false' />" +
		"</div>" +
		"<div class='comment-send'>" +
		"<a href='#' type='submit' data-theme='z' id='comment-send' data-role='button' data-mini='true' " +
		"onclick='sendComment("+ boardId +")'>쓰기</a>" +
		"</div>" +
		"<div class=clear></div>"+
	"</div>	</li><li>&nbsp;</li>");
	boardComment.trigger("create");

    $.ajax({
        url : url + "/moimserver/json/member/commentList.json?boardId=" + boardId,
        dataType : "jsonp",
        crossDomain:true,
        jsonp : "callback",
        success : function(jsonData){
        	$.each(jsonData.boars, function(k, v) {
        		var nickname="";
        		var profileId;
        		var len = moimMemArray.length;
        		for(var i=0; i < len; i++) {
        			if(moimMemArray[i].id == v.memberId) {
        				console.log("[attachComment] " + moimMemArray[i].id + " / " + v.memberId);
        				nickname = matchUser(moimMemArray[i].userId, 'nickname');
        				profileId = moimMemArray[i].userId;
        				break;
        			}
        		}
        		boardComment.append(
        				"<li class='comment'>" + 
        					"<img src='img/p" + profileId + ".jpg' />" +
        					"<div class='comment_name'>" + nickname + "</div>" +
        					"<div class='comment_content'>" + v.content + "</div>" +
        					"<div class='clear'></div>" +
        				"</li>");
        	});
        	$("#ajax").show();
        }
		
	}); //ajax

	return true;
}

function sendComment(boardId) {
	
	var comment_content = document.getElementById("comment_text_" + boardId).value;
	
	$.ajax({
	       url: url + "/moimserver/json/member/writeComment.json",
	       type: 'GET',
           crossDomain:true,
           jsonp : "callback",
	       contenttype:'application/json; charset=utf-8',
	       data: {
	    	  boardId: boardId,
	          content: comment_content,
	          userId: current_memId
	       },
	       dataType:'jsonp',
	       success: function(jsonData) {
	    		console.log("[sendComment] success " +jsonData.result);
	    		$.mobile.changePage(
	    			    window.location.href,
	    			    {
	    			      allowSamePageTransition : true,
	    			      transition              : 'none',
	    			      showLoadMsg             : false,
	    			      reloadPage              : true
	    			    }
	    			  );
	       }
	});
}

/********Plaza***********/
function plazaWrite() {
	var title = document.getElementById("title").value;
	var content = document.getElementById("write-textarea").value;
	$.ajax({
	       url: url + "/moimserver/json/plaza/writePlaza.json",
	       type: 'GET',
           crossDomain:true,
           jsonp : "callback",
	       contenttype:'application/json; charset=utf-8',
	       data: {
	    	  moimId : current_moim,
	          title: title,
	          content:content
	       },
	       dataType:'jsonp', 
	       success: function(jsonData) {
	    		console.log("[plazaWrite] board write done:" + jsonData.result);
	    		$.mobile.changePage("plaza.jsp");
	       }
	});
}

function plazaList() {

    $.ajax({
        url : url + "/moimserver/json/plaza/List.json?moimId=" + current_moim,
        dataType : "jsonp",
        crossDomain:true,
        jsonp : "callback",
        success : function(jsonData){
        	/* think about how to get profile image...
        	 * board folded view안에 조회수랑 쓰기자이름, 작성일 등등 표기할 구성 생각해보*/
        	$.each(jsonData.boars, function(k, v) {
        		var notCollap = "";
        		if(k == 0) {
        			notCollap = " data-collapsed='false'";
        		}
        		$('#plaza-list').prepend(
        				"<div data-role='collapsible' data-icon='arrow-d' data-iconpos='right' " + 
        				notCollap + "data-theme='z' data-content-theme='d'>" +
        				"<h4>" +
        				"<span class='rtitle'>" + v.title + "</span>" + 
        				"<div class='date'>" + v.regdate + "</div>" + 
        				"</h4>" + 
        				"<p>" + v.content +"</p>" +
        				"<fieldset data-role='controlgroup' data-type='horizontal' style='text-align:right;' id='btn_" +v.id + "' >" +
        				"<a href='#' onclick='toPlazaBoardWrite("+ v.id + ")' data-role='button' data-theme='z' data-mini='true'>관련글쓰기</a>" +
        				"</fieldset>" +
        				"<div id='plaza_" + v.id + "'></div> </div>");
        		
        		if(current_pos == 'king') {
        			$("#btn_" + v.id).append(
            				"<a href='#' onclick='update(&#39;board&#39;, " + v.id + ")' data-role='button' data-theme='z' data-mini='true'>수정</a>" +
            				"<a href='#' onclick='remove_item(&#39;board&#39;, " + v.id + ")' data-role='button' data-theme='z' data-mini='true'>삭제</a>");
        		}
        		
        		attachPlazaBoard(v.id);
        		$('#plaza-list').trigger('create');
        		
        	});
        	$("[data-role=\"collapsible\"]").collapsible();
        	$("#ajax").show();
        }
		
	}); //ajax
}

function toPlazaBoardWrite(plazaId) {
	$.mobile.changePage("plaza_board_write.jsp");
	localStorage.setItem("plazaIdToWrite", plazaId);
}

function plazaBoardWrite() {
	var title = document.getElementById("title").value;
	var content = document.getElementById("write-textarea").value;
	var plazaId = localStorage.getItem("plazaIdToWrite");
	$.ajax({
	       url: url + "/moimserver/json/plaza/writeBoard.json",
	       type: 'GET',
           crossDomain:true,
           jsonp : "callback",
	       contenttype:'application/json; charset=utf-8',
	       data: {
	    	  plazaId : plazaId,
	          title: title,
	          content:content,
	          userId: userid
	       },
	       dataType:'jsonp', 
	       success: function(jsonData) {
	    		console.log("[plazaBoardWrite] board write done:" + jsonData.result);
	    		localStorage.removeItem("plazaIdToWrite");
	    		$.mobile.changePage("plaza.jsp");
	       }
	});
}

function attachPlazaBoard(plazaId) {

	var attachTo = $("#plaza_"+plazaId);
    $.ajax({
        url : url + "/moimserver/json/plaza/boardList.json?plazaId=" + plazaId,
        dataType : "jsonp",
        crossDomain:true,
        jsonp : "callback",
        success : function(jsonData){
        	/* think about how to get profile image...
        	 * board folded view안에 조회수랑 작성자이름, 작성일 등등 표기할 구성 생각해보*/
        	$.each(jsonData.boars, function(k, v) {
        		var notCollap = "";
        		if(k == 0) {
        			notCollap = " data-collapsed='false'";
        		}
        		console.log("[attachPlazaBoard] " + matchUser(v.userId, 'nickname'));
        		attachTo.append(
        				"<div data-role='collapsible' data-icon='arrow-d' data-iconpos='right' " + 
        				notCollap + "data-theme='z' data-content-theme='d' id='plaza_board_'" + v.id + "'>" +
        				"<h4>" +
        				"<div class='author'><img src='img/p"+ v.userId + ".jpg' alt='profile'><br/>" +
        				matchUser(v.userId, 'nickname') + "</div>" +
        				"<span class='rtitle'>" + v.title + "</span>" + 
        				"<div class='date'>" + v.regdate + "</div>" + 
        				"</h4>" + 

        				"<p>" + v.content +"</p>" +
        				"<fieldset data-role='controlgroup' data-type='horizontal' style='text-align:right;' id='btn_" +v.id + "'>" +
        				"</fieldset>" +
        				"<ul id='plaza_comment_" + v.id + "'></ul></div>");
        		
        		if(userid == v.userId) {
        			$("#btn_" + v.id).append(
            				"<a href='#' onclick='update(&#39;board&#39;, " + v.id + ")' data-role='button' data-theme='z' data-mini='true'>수정</a>" +
            				"<a href='#' onclick='remove_item(&#39;board&#39;, " + v.id + ")' data-role='button' data-theme='z' data-mini='true'>삭제</a>");
        		}
        		
        		attachPlazaComment(v.id);
        		attachTo.trigger('create');
        		
        	});
        	$("[data-role=\"collapsible\"]").collapsible();
        	$("#ajax").show();
        }
		
	}); //ajax
}

function attachPlazaComment(boardId) {
	var boardComment = $("#plaza_comment_" + boardId);
	//댓글작성부
	boardComment.append ("<li class='comment_write'>" + 
	"<div style='width:100%;'>" +
		"<div class='comment-text' >" +
		"<input type='text' id='comment_text_" + boardId  + "' name='comment_text_" + boardId  + "' data-mini='true'"+
		"data-corners='false' />" +
		"</div>" +
		"<div class='comment-send'>" +
		"<a href='#' type='submit' id='comment-send' data-role='button' data-theme='z' data-mini='true' " +
		"onclick='sendPlazaComment("+ boardId +")'>쓰기</a>" +
		"</div>" +
		"<div class=clear></div>"+
	"</div>	</li><li>&nbsp;</li>");
	boardComment.trigger("create");

    $.ajax({
        url : url + "/moimserver/json/plaza/commentList.json?boardId=" + boardId,
        dataType : "jsonp",
        crossDomain:true,
        jsonp : "callback",
        success : function(jsonData){
        	/* think about how to get profile image...
        	 * board folded view안에 조회수랑 작성자이름, 작성일 등등 표기할 구성 생각해보*/
        	$.each(jsonData.boars, function(k, v) {
        		boardComment.append(
        				"<li class='comment'>" + 
        					"<img src='img/p" + v.userId + ".jpg' />" +
        					"<div class='comment_name'>" + matchUser(v.userId, 'nickname') + "</div>" +
        					"<div class='comment_content'>" + v.content + "</div>" +
        					"<div class='clear'></div>" +
        				"</li>");
        	});
        	$("#ajax").show();
        }
		
	}); //ajax

	return true;
}

function sendPlazaComment(boardId) {
	
	var comment_content = document.getElementById("comment_text_" + boardId).value;
	
	$.ajax({
	       url: url + "/moimserver/json/plaza/writeComment.json",
	       type: 'GET',
           crossDomain:true,
           jsonp : "callback",
	       contenttype:'application/json; charset=utf-8',
	       data: {
	    	  boardId: boardId,
	          content: comment_content,
	          userId: userid
	       },
	       dataType:'jsonp',
	       success: function(jsonData) {
	    		console.log("[sendPlazaComment] success " + jsonData.result);
	    		$.mobile.changePage(
	    			    window.location.href,
	    			    {
	    			      allowSamePageTransition : true,
	    			      transition              : 'none',
	    			      showLoadMsg             : false,
	    			      reloadPage              : true
	    			    }
	    			  );
	       }
	});
	
}

/***drag drop ******/
var width=38;

var toView = [];
var userArray = [];
var moimMemArray = [];

var inUsers = [];
var exUsers = [];

var cur_moving;
var cur_idx;

var status; //1 for board, 0 for boardlist

function getMembers(stat) {
	moimMemArray=[];

	inUsers = [];
	exUsers = [];
	
	cur_moving = -1;
	cur_idx = -1;

	status = stat;
	
	getMembers_member();
	
//	$.ajax({
//        url : url + "/moimserver/json/moim/usernameList.json?id=" + current_moim,
//        dataType : "jsonp",
//        crossDomain:true,
//        jsonp : "callback",
//        success : function(jsonData){
//        	$.each(jsonData.user, function(k, v) {
//        		moimUserArray.push({'nickname':v.nickname, 'name' : v.name, 'id':v.id});
//        	});
//        	$("#ajax").show();
//        	
//        	getMembers_member();
//        }
//	}); //ajax
}

function getMembers_member(){

	$.ajax({
        url : url + "/moimserver/json/moim/userList.json?id=" + current_moim,
        dataType : "jsonp",
        crossDomain:true,
        jsonp : "callback",
        success : function(jsonData){
        	$.each(jsonData.member, function(k, v) {
        		moimMemArray.push({'userId':v.userId, 'pos' : v.position, "id": v.id});
        	});
        	
        	/*******/
        	if(status == 1) {
        		console.log("[getMembers_member] " + toView.length );
        		addToArray();
        	} else if(status == 0) {
        		var tmparray = [];
        		var len = moimMemArray.length;
        		for(var i=0; i < len; i++) {
        			if(moimMemArray[i].pos != 'man') {
        				tmparray.push({"memId": moimMemArray[i].id, "userId": moimMemArray[i].userId});
        			}
        		}
        		printProfiles(tmparray, 'div.profile div.imgs');
        		boardMain();
        	}
        	$("#ajax").show();
        }
	}); //ajax
}

function addToArray() {
	var len = moimMemArray.length;
	
	for(var i=0; i < len; i++) {
		var tmp = moimMemArray[i];
		if(tmp.pos != "man") {
			var incl = $.inArray(tmp.id, toView);
			var item = {'nickname' : matchUser(tmp.userId, 'nickname'), 'name' :  matchUser(tmp.userId, 'name'), 
					'memId': tmp.id, "userId": tmp.userId};
			if(incl != -1) {
				console.log("[getMembers] in " + tmp);
				inUsers.push(item);
			} else {
				console.log("[getMembers] ex " + tmp);
				exUsers.push(item);
			}
		}
	}
	
	printProfiles(inUsers, '.member_included');
	printProfiles(exUsers, '.member_excluded');
	
	boardList(inUsers, inUsers.length);
	
	dndInit();
}

function printProfiles(array, target) {
	var len = array.length;
	console.log("[printProfiles]");
	for(var i = 0; i < len; i++) {
		$(target).append(
				"<div><a href='#' ontouchstart='moving(" + array[i].memId + 
				")'><img src='img/p" + array[i].userId%11 + ".jpg'></a></div>"
		);
	}
}

function moving (id) {
	cur_moving = id;
	console.log("[moving] " + cur_moving + " / " + cur_idx);
}

function matchUser(userId, type) {
	var len = userArray.length;
	for(var i=0; i < len; i++) {
		if(userId == userArray[i].id) {
			return (type == "nickname")? userArray[i].nickname : userArray[i].name;
		}
	}
	return "";
}

function dndInit() {
	num = 0;
	
	reloc(".member_excluded");
	reloc(".member_included");
	
	var inarray = $(".member_included div");
	var exarray = $(".member_excluded div");

	for(var i=0; i < inarray.length; i++) {
		draggable($(inarray[i]), ".member_excluded");
	}
	for(var i=0; i<exarray.length; i++) {
		draggable($(exarray[i]), ".member_included");
	}

	dropable(".member_included");
	dropable(".member_excluded");
	
	$.drop({ mode:"middle" });
}

function draggable(target, toDrop) {
	var $div = $("#container");

	var inmem = $(".member_included img").length;
	var exmem = $(".member_excluded img").length;
	
	$(target)
	.drag("start",function( ev, dd ){
			dd.limit = $div.offset();
			dd.limit.bottom = dd.limit.top + $div.outerHeight() - $( this ).outerHeight();
			dd.limit.right = dd.limit.left + $div.outerWidth() - $( this ).outerWidth();
		})
	.drag(function( ev, dd ){
		$( this ).css({
			top: Math.min( dd.limit.bottom, Math.max( dd.limit.top, dd.offsetY ) ),
			left: Math.min( dd.limit.right, Math.max( dd.limit.left, dd.offsetX ) )
		}); 
	}, { drop: toDrop })
	.drag('end', function (ev, dd) {
		if($(dd.drop).attr('class') != $(dd.available).attr('class')) {
			$( this ).animate({
				top: dd.originalY,
				left: dd.originalX
			}, 10 );
			cur_moving = -1;
			cur_idx = -1;
		}
	}); //drag
}
function dropable(toDrop) {

	$(toDrop).drop(function (ev, dd) {
		console.log("dropped");
		$(dd.target).append(dd.drag);
		
		var inmem = $(".member_included div").length;
		var exmem = $(".member_excluded div").length;
		
		var toDropNext = "";
		var num=0;
		if(toDrop == '.member_included') {
			toDropNext = '.member_excluded';
			num = inmem;
			
			var len = exUsers.length;
			for(var i = 0; i < len; i++) {
				var tmp = exUsers[i];
				if(tmp.memId == cur_moving) {
					cur_idx = i;
					break;
				}
			}
			inUsers.push(exUsers[cur_idx]);
			exUsers.splice(cur_idx, 1);
		}
		else if(toDrop == '.member_excluded') {
			toDropNext = '.member_included';
			num = exmem;
			
			var len = inUsers.length;
			for(var i = 0; i < len; i++) {
				var tmp = inUsers[i];
				if(tmp.memId == cur_moving) {
					cur_idx = i;
					break;
				}
			}
			exUsers.push(inUsers[cur_idx]);
			inUsers.splice(cur_idx, 1);
		}
		
		$(dd.drag).animate({
			left: width*num,
			top: $(toDrop).offset().top
		}, 10);
		
		draggable($(dd.drag), toDropNext);
		reloc('.member_included');
		reloc('.member_excluded');
		
		var len = inUsers.length;
		toView = [];
		for (var i=0; i <len; i++) {
			toView.push(inUsers[i].memId);
		}
		
		if(cleanBoard()) {
			boardList(inUsers, len);
		}
	});
}

function reloc(divName) {
	var array = $(divName + " div");
	var len = array.length;
	
	for(var i = 0; i < len; i++) {
		$(array[i]).animate({
			left: width*i
		});
	}

	$(divName).trigger('create');
}

function cleanBoard() {
	$("#board-list").empty();
	return true;
}

/*******BoardMain*******/
var center;
var centery;
var centerx;
function boardMain() {
	toView = [];
	centery = $(window).height()/2;
	centerx = $(window).width()/2;
	
	$("div.center").click(function () {
		$.mobile.changePage("board.jsp");
	});
	
	var array = $(".profile div");
	var n = array.length;
	for(var i=0; i < n; i++) {
		$(array[i]).css({
			left:centerx,
			top:centery
		});
	}
	center = $(".center");
	$(center).css({
		left:centerx - center.width()/2,
		top:centery - center.height()/2
	});
	reloc2();
	
	$(".profile").trigger('create');
	$.drop({ mode:"middle" });
	
	var array = $(".imgs div");
	var n = array.length;
	for(var i = 0 ; i < n ; i ++)
		draggable2(array[i],".center");
	dropable2(".center");
	reloc2();
}

function draggable2(target, toDrop) {
	
	var check = false;
	$(target)
	.drag("start",function( ev, dd ){
		})
	.drag(function( ev, dd ){
		if(check == false) {
			$( this ).css({
				top: dd.offsetY,
				left: dd.offsetX,
				border:'1px solid #aaaaaa' 
			}); 
		}
	}, { drop: toDrop })
	.drag('end', function (ev, dd) {
		if( check == false && $(dd.drop).attr('class') != $(dd.available).attr('class')) {
			$( this ).animate({
				top: dd.originalY,
				left: dd.originalX
			}, 10 );
		} else {
			console.log("no revert");
			check = true;
			return;
		}
	
	}); //drag
}
function draggstop(target) {
	
}
function dropable2(toDrop) {

	$(toDrop)
	.drop('start', function(ev, dd) {
		$(this).addClass("active");
	})
	.drop(function (ev, dd) {
		console.log("dropped");

		$(dd.target).append(dd.drag);
		toView.push(cur_moving);
		
		reloc2();
		reloc22();
	})
	.drop('end', function(ev, dd) {
		$(this).removeClass("active");
	});
}

function reloc2() {
	var array = $(".imgs div");
	var n = array.length;
	var r = centerx*7/10;
	var angle = 360/n;
	
	for(var i=0; i < n; i++) {
		var x = centerx + Math.sin(Math.PI/180 * angle * i) * r;
		var y = centery - Math.cos(Math.PI/180 * angle * i) * r;
		$(array[i]).animate({
			left:x - 25,
			top:y - 25
		});
	}
}
function reloc22() {
	var array = $(".center div");
	var n = array.length;
	var r = centerx*2/10;
	var angle = 360/n;
	
	for(var i=0; i < n; i++) {
		$(array[i]).css({
			left:center.width()/2 - $(array[i]).width()/2,
			top:center.height()/2 - $(array[i]).height()/2
		});
		
		var x = Math.sin(Math.PI/180 * angle * i) * r;
		var y = Math.cos(Math.PI/180 * angle * i) * r;
		$(array[i]).animate({
			left:x + center.width()/2 - $(array[i]).width()/2,
			top:y + center.height()/2 - $(array[i]).height()/2
		}, 100);
	}
}

/******유저아이디로 검색해서 가입 *******/
function findUsersMoims() {
	var idToSearch = document.getElementById('id_to_search').value;
	
	var len = userArray.length
	var exist = false;
	for(var i=0; i < len; i++) {
		if(userArray[i].name == idToSearch) {
			exist = true;
		}
	}

	if(!exist) {
		$("#errormsg").text('존재하지 않는 유저입니다.');
		return;
	}
	$.mobile.changePage("user_moim_list.jsp");
	userMoimList(idToSearch);
}

function userMoimList(userName) {
	var array = [];
	console.log("[userMoimList] " + userName);

    $.ajax({
        url : url + "/moimserver/json/user/login.json?name=" + userName,
        dataType : "jsonp",
        crossDomain:true,
        jsonp :"callback",
        success : function(jsonData){
			$.each(jsonData, function(k, v) { 
				array.push(v.Moim);
			});
			
			array.sort();
			$.each(array, function(k, v) {
				$("#user_moim_list").append('<input type="checkbox" name="cb-'+k+'" id="cb-'+k+
		    			 '" value="'+v.id+'"/><label for="cb-'+k+'">'+v.title+'</label>');
			});
			
			$("#user_moim_list").trigger('create');
        }
		
	}); //ajax (JSON)
   
    
}

function joinMoim() {
	var array=[];
	var len = $("#user_moim_list input:checked").length;
	
	for(var i=0; i < len; i++) {
		console.log("[joinMoim] " + $("#user_moim_list input:checked")[i].value);
		array.push( {"moimid" : $("#user_moim_list input:checked")[i].value});
	}

	$.when(addMultipleMoims(array, array.length)).then(function() {
		$.mobile.changePage('moim_list.jsp');
	});
}

function addMultipleMoims(array, i) {
	if(i <= 0) {
		console.log("[addMultipleMoims] done");
		return;
	}
	
	console.log("[addMultipleMoims] " + array[i-1].moimid);
	$.ajax({
	       url: url + "/moimserver/json/user/addMoim.json",
	       type: 'GET',
	       contenttype:'application/json; charset=utf-8',
	       crossDomain:true,
	       data: {
	          name: name,
	          moimId: parseInt(array[i-1].moimid),
	          pos: 'man'
	       },
	       dataType:'jsonp',
	       success: function(jsonData) {
	    	   addMultipleMoims(array, i-1);
	       },
	       error: function() {
	    	   console.log("[addMember] errorr...");
	       }
	}); //ajax
}

/*****saveUSerARray******/
function userList() {
	$.ajax({
        url : url + "/moimserver/json/user/list.json",
        dataType : "jsonp",
        crossDomain:true,
        jsonp : "callback",
        success : function(jsonData){
			$.each(jsonData, function (k, v) {
				userArray.push({"id":v.id, "name": v.name, "nickname": v.nickname});
			});
        }
	}) 
}

/***********delete *********/
function remove_item(thing, id) {
	console.log("[remove] (" + thing + ") id " + id);
	var ajax_url = "";
	var dataToSend;
	var redirectTo = "";
	if(thing == "moim"){
	} else if(thing == "board") {
		ajax_url = url + "/moimserver/json/member/deleteBoard.json";
		dataToSend = {boardId : id};
		redirectTo = "board.jsp";
	} else if(thing == 'plaza') {
		ajax_url = url + "/moimserver/json/plaza/deletePlaza.json";
		dataToSend = {plazaId : id};
		redirectTo = "plaza.jsp";
	} else if(thing == 'pb') {
		ajax_url = url + "/moimserver/json/plaza/deleteBoard.json";
		dataToSend = {boardId : id};
		redirectTo = "plaza.jsp";
	} else if(thing = 'board_comment') {
		ajax_url = url + "/moimserver/json/member/deleteComment.json";
		dataToSend = {commentId : id};
		redirectTo = "board.jsp";
	}
	
	$.ajax({
	       url: ajax_url,
	       type: 'GET',
	       crossDomain:true,
	       jsonp : "callback",
	       contenttype:'application/json; charset=utf-8',
	       data: dataToSend,
	       dataType:'jsonp', 
	       success: function(jsonData) {
	    		console.log("[remove] (" + thing + "):" + jsonData.result);
	    		$.mobile.changePage(
	    			    window.location.href,
	    			    {
	    			      allowSamePageTransition : true,
	    			      transition              : 'none',
	    			      showLoadMsg             : false,
	    			      reloadPage              : true
	    			    }
	    			  );
	       }
	});
	
}

/******* update **********/
function updateInit(thing) {
		var boardId = localStorage.getItem("id_to_update");
		var title = localStorage.getItem("title_to_update");
		var content = localStorage.getItem("content_to_update");
		
		$("#title").val(title);
		$("#write-textarea").val(content);
		
		$("#update_board_btn").click (function () {
			localStorage.removeItem("id_to_update");
			localStorage.removeItem("title_to_update");
			localStorage.removeItem("content_to_update");
			
			console.log("[update_plaza] submit clicked");
			updateSubmit(thing, boardId);
		});
}
function update(thing, id) {
	console.log("[update] (" + thing + ") id " + id);
	var ajax_url = "";
	var dataToSend;
	var redirectTo = "";
	
	if(thing == "board") {
		ajax_url = url + "/moimserver/json/member/getBoard.json?boardId=";
		redirectTo = "update_board.jsp";
	} else if(thing == 'plaza') {
		ajax_url = url + "/moimserver/json/plaza/getPlaza.json?plazaId=";
		dataToSend = {plazaId : id};
		redirectTo = "update_plaza.jsp";
	} else if(thing == 'pb') {
		ajax_url = url + "/moimserver/json/plaza/getBoard.json?boardId=";
		dataToSend = {boardId : id};
		redirectTo = "update_pb.jsp";
	}
	
	$.ajax({
        url : ajax_url + id,
        dataType : "jsonp",
        crossDomain:true,
        jsonp : "callback",
        success : function(jsonData){
    		console.log("[update] : success");
    		localStorage.setItem("title_to_update", jsonData.boars.title);
    		localStorage.setItem("content_to_update", jsonData.boars.content);
    		localStorage.setItem("id_to_update", id);
    		$.mobile.changePage(redirectTo);
        	$("#ajax").show();
        }
	}); //ajax
}

function updateSubmit(thing, id) {
	console.log("[updateSubmit] (" + thing + ") id " + id);
	var ajax_url = "";
	var dataToSend;
	var redirectTo = "";
	if(thing == "moim"){
	}
	else if(thing == "board") {
		ajax_url = url + "/moimserver/json/member/updateBoard.json";
		dataToSend = {boardId : id, 
				title: document.getElementById('title').value,
				content: document.getElementById('write-textarea').value};
		redirectTo = "board.jsp";
	}
	else if(thing == "plaza") {
		ajax_url = url + "/moimserver/json/plaza/updatePlaza.json";
		dataToSend = {boardId : id, 
				title: document.getElementById('title').value,
				content: document.getElementById('write-textarea').value};
		redirectTo = "plaza.jsp";
	}
	else if(thing == "pb") {
		ajax_url = url + "/moimserver/json/plaza/updateBoard.json";
		dataToSend = {boardId : id, 
				title: document.getElementById('title').value,
				content: document.getElementById('write-textarea').value};
		redirectTo = "plaza.jsp";
	}
	
	$.ajax({
	       url: ajax_url,
	       type: 'GET',
	       crossDomain:true,
	       jsonp : "callback",
	       contenttype:'application/json; charset=utf-8',
	       data: dataToSend,
	       dataType:'jsonp', 
	       success: function(jsonData) {
	    		console.log("[updateSubmit] (" + thing + "):" + jsonData.result);
	    		$.mobile.changePage(redirectTo);
	       }
	});
	
}

/********액티비티 실행*******/
function runChat(){
	console.log("[runChat]");
	cordova.exec(startActivityOK, startActivityFail, "ActivityRunPlugin", "chatAction", [nick, current_moim] );
}

function startActivityOK() {
	console.log("[startActivityOK]");
}

function startActivityFail() {
	console.log("[startActivityFail]");
}
/*****Login *********/
function login() { 
	var username = document.getElementById("j_username").value;
	var pass = document.getElementById("j_password").value;

	console.log("[login] trying :" + username + "/" + pass);
	$.ajax({
	       url: url + "/moimserver/json/user/loginCheck.json",
	       type: 'GET',
	       contenttype:'application/json; charset=utf-8',
	       data: {
	    	   j_username: username,
	    	   j_password: pass
	       },
	       dataType:'jsonp',
	       crossDomain: true,
	       jsonp: "callback",
	       success: function(jsonData) {
	    	   var result = jsonData.result;
	    	   console.log("[login] : " + result);
	    	   if(result == 'fail') {
	    		   $("#error").text("아이디나 패스워드가 틀렸습니다.");
	    	   } else if(result == 'notRegistered') {
	    		   $("#error").text("아이디가 존재하지 않습니다.");
	    	   } else if(result == 'success') {
	    		   name = jsonData.username;
	    		   userid = jsonData.userid;
	    		   nick = jsonData.nickname;
	    		   console.log("[login] current user: " + name + "/" + userid);
	    		   $.mobile.changePage("moim_list.jsp");
	    	   }
	       }
	});
}


/*** logout button..?**/
var logoutOpen = false;

function onMenuKeyDown() {
	console.log("[onMenuKeyDown] menu key tapped");

	if(logoutOpen){
		console.log("[onMeueKeyDown] close Logout");
		$("#logout_panel").animate({bottom: '-=57px'}, 200);	
		$("#logout_panel").css({display:'none'});
		logoutOpen = false;
	} else {
		console.log("[onMeueKeyDown] open Logout");
		$("#logout_panel").animate({bottom: '+=57px'}, 200);
		$("#logout_panel").css({display:'block'});
		logoutOpen = true;
	}
	
}

function logout() {
	console.log("[logout]");
	name = "";
	userid = -1;
	nick = "";
	current_moim_title="";
	logoutOpen = false;
	$.mobile.changePage("login.jsp");
	document.getElementById("j_username").value="";
	document.getElementById("j_password").value="";
}

/***upload photo *********/
function uploadImage() {
	navigator.camera.getPicture(uploadPhoto,
        function(message) { alert('get picture failed'); },
        { quality: 50, 
        destinationType: navigator.camera.DestinationType.FILE_URI,
        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
        );
}

function uploadPhoto(imageURI) {
    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
    options.mimeType="image/jpeg";

    var params = {};
    params.value1 = "test";
    params.value2 = "param";

    options.params = params;

    var ft = new FileTransfer();
    ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
}

function win(r) {
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
}

function fail(error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}

/*********function on load every page **********************/
$(function() {
	document.addEventListener("deviceready", onDeviceReady, false);
	console.log("document ready");
	
	$.mobile.defaultPageTransition = 'slide';
	
	userList();
	
	// db준비
	dbinit();
	// device가 준비되면 table을 준비한다.
	db.transaction(setupTable, dbErrorHandler, successCB);
	//perform board-write

	$("#writebutton").click(function() {
		
		//안드로이드 로컬 디비에 저장하는 테스트..
		console.log("write submit button clicked");
        $.ajax({
            url : "http://edu.sunnyvale.co.kr/C4Db/api/1.0/list.json",
            dataType : "jsonp",
            jsonp : "callback",
            success : function(jsonData){

				db.transaction(function(tx){
            		tx.executeSql('delete from MOIM_BOARD');
            	}, dbErrorHandler, successCB);
				
				$.each(jsonData.list, function(k, v) {
					
					db.transaction(function(tx) {
						tx.executeSql('INSERT INTO MOIM_BOARD (title, content, regdate) VALUES(?,?,?)',
								[v.title, v.url, v.createDate]);
					},dbErrorHandler, successCB); 
				});
            }
			
		}); //getJSON

		console.log("done insertion");
	}); //write_submit_btn



}); // document.ready
